package com.qyl.hrm.utils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

/**
 * ExcelUtils
 */
public class ExcelUtils {
	
	

	/**
	 * 导出EXCEL
	 * @param excelFileName 生成EXCEL文件名称
	 * @param sheetName 工作单的名称
	 * @param titles 标题行
	 * @throws Exception 
	 */
	public static void exportExcel(String excelFileName, String sheetName,
			String[] titles, List<?> data, HttpServletResponse response,HttpServletRequest request) throws Exception {
		// 创建工作簿
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 创建工作单
		HSSFSheet sheet = workbook.createSheet(sheetName);
		
		
		// 创建第一行做为标题行
		HSSFRow row = sheet.createRow(0);
		// 第一行中的列
		for (int i = 0; i < titles.length; i++){
			// 创建列
			HSSFCell cell = row.createCell(i);
			// 设置列中的值
			cell.setCellValue(titles[i]);
		}
		
		
		// ------ 生成Excel内容部分 ------
		for (int i = 0; i < data.size(); i++){
			// 获取一个对象,该对象生成一行数据
			Object obj = data.get(i);
			// 创建一行
			row = sheet.createRow(i + 1);
			// 根据对象中的字段,创建列
			Field[] fields = obj.getClass().getDeclaredFields();
			for (int j = 1; j < fields.length; j++){
				
				// 创建列
				HSSFCell cell = row.createCell(j-1);
				
				// 获取该字段的值
				Field field = fields[j];
				// 设置字段可以访问
				field.setAccessible(true);
				Object res = field.get(obj);
				// 设置列中的值
				cell.setCellValue(res != null ? res.toString() : "");
			
			}
		}
		
		
		// 获取浏览器类型
		String userAgent = request.getHeader("user-agent");
		if (userAgent.toLowerCase().indexOf("msie") != -1){
			excelFileName = URLEncoder.encode(excelFileName, "utf-8");
		}else{
			excelFileName = new String(excelFileName.getBytes("utf-8"), "iso8859-1");
		}
		// 设置导出的文件名
		response.setHeader("Content-Disposition", "attachment;filename="+ excelFileName +".xls");
		// 输出
		workbook.write(response.getOutputStream());
	}

	
	
	
}	
